package com.maochd.cloud.excel.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.maochd.cloud.api.goods.domain.entity.GoodsInfo;
import com.maochd.cloud.api.goods.service.RemoteGoodsService;
import com.maochd.cloud.common.core.domain.BizListWrap;
import com.maochd.cloud.common.core.domain.R;
import com.maochd.cloud.common.core.utils.bean.BeanConvertUtil;
import com.maochd.cloud.excel.annotation.ImportMethod;
import com.maochd.cloud.excel.dto.ImportDto;
import com.maochd.cloud.excel.dto.excel.ImportGoodsExcel;
import com.maochd.cloud.excel.enums.ImportEnum;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ImportBusinessServiceImpl {

    @Resource
    private RemoteGoodsService remoteGoodsService;

    @ImportMethod(type = ImportEnum.IE_1001, clazz = ImportGoodsExcel.class)
    public List<ImportGoodsExcel> importGoods(ImportDto dto) {
        if (CollUtil.isEmpty(dto.getList())) {
            return Lists.newArrayList();
        }
        List<GoodsInfo> goodsInfoList = BeanConvertUtil.convertListTo(dto.getList(), GoodsInfo::new);
        // 批量插入
        R<List<GoodsInfo>> batchResult = remoteGoodsService.batchInsert(new BizListWrap<>(goodsInfoList));
        List<ImportGoodsExcel> importGoodsList;
        if(R.isNotOk(batchResult)) {
            importGoodsList = BeanConvertUtil.convertListTo(goodsInfoList, ImportGoodsExcel::new);
            importGoodsList.forEach(f -> f.setFailReason(batchResult.getBizMsg()));
            return importGoodsList;
        }
        // 返回失败数据
        return BeanConvertUtil.convertListTo(batchResult.getData(), ImportGoodsExcel::new);
    }
}
